package cn.itcast.service;

import cn.itcast.entity.ExamInfo;
import cn.itcast.entity.Question;
import cn.itcast.entity.QuestionInfo;
import cn.itcast.entity.User;
import cn.itcast.exception.LoginException;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class ExamServiceImpl
        implements ExamService, Serializable {
    private static final long serialVersionUID = -89697097419788051L;

    /**
     * 是否已经开始答题
     */
    private boolean started = false;
    /**
     * 是否已经答题结束
     */
    private boolean finish = false;
    private User publicUser;
    private List<QuestionInfo> questionInfoList = new ArrayList<>();

    @Override
    public User login(String id, String pwd) {
        //判断id是否为数字,密码是否符合规范
        //正则表达式
        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
        boolean matches = pattern.matcher(id).matches();
        if ("".equals(id)) {
            throw new LoginException("id不能为空");
        }
        if (!matches || "".equals(id)) {
            throw new LoginException("id必须是数字");
        }
        // 判断password是否匹配regex中定义的规则
        // 正则表达式:表示：6位数、包含大小字母、小写字母、数字和特殊符号  的正则表达式
        String regex = "^(?![A-Za-z0-9]+$)(?![a-z0-9\\W_]+$)(?![A-Za-z\\W_]+$)(?![A-Z0-9\\W_]+$)[\\w\\W]{6,}$";
        boolean result = pwd.matches(regex);
        if ("".equals(pwd)) {
            throw new LoginException("密码不能为空");
        }
        if (!result) {
            throw new LoginException("密码必须是6位数、包含大小字母、小写字母、数字和特殊符号");
        }

        // 实现登录功能
        User user = new User(Integer.parseInt(id), pwd);
        ArrayList<User> ListUser = getArraysList();
        //比较键盘录入的id,与密码是否与集合中的一致
        publicUser = checkLongin(ListUser,user);
        return publicUser;
    }

    private User checkLongin(ArrayList<User> User, User user) {
        for (User listUser : User) {
            if (listUser.equals(user)) {
                return listUser;
            }
        }

        throw new LoginException("账号或密码不正确");
    }

    /**
     * 获取第一道题
     *
     * @return
     */
    @Override
    public QuestionInfo getCurrentQuestion(int index) {
        BufferedReader br = null;
        List<Question> questionList = new ArrayList<>();
        try {
            br = new BufferedReader(new FileReader("questions.txt"));
            String line;
            while ((line = br.readLine()) != null) {

                Question question = new Question();
                String[] split = line.split("[@|,][a-z]+=");
                String[] split1 = split[1].split("/");
                List<Integer> list = new ArrayList<>();
                for (String s : split1) {
                    list.add(Integer.parseInt(s));
                }
                question.setAnswer(list);
                question.setScore(Integer.parseInt(split[2]));
                question.setLevel(Integer.parseInt(split[3]));
                question.setTitle(br.readLine());
                List<String> options = new ArrayList<>();
                for (int i = 0; i < 4; i++) {
                    options.add(br.readLine());
                    question.setOptions(options);
                }
                questionList.add(question);
            }

                //根据难度级别分组
                Map<Integer, List<Question>> map =
                        questionList.stream().collect(Collectors.groupingBy(Question::getLevel));

                //十个等级
                Random r = new Random();
                int count = 0;
                for (int i = 1; i <= 10; i++) {
                    //当前这个等级的所有题集合 从这个集合中随机找出两个题
                    List<Question> questions = map.get(i);


                    int i1 = r.nextInt(questions.size());
                    int i2 = r.nextInt(questions.size());
                    if (i1 == i2) {
                        i2 = r.nextInt(questions.size());
                    }
                    QuestionInfo questionInfo1 = new QuestionInfo(count, questions.get(i1));
                    count++;
                    QuestionInfo questionInfo2 = new QuestionInfo(count, questions.get(i1));
                    count++;
                    questionInfoList.add(questionInfo1);
                    questionInfoList.add(questionInfo2);

                }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(br != null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

        return questionInfoList.get(index);
}

    /**
     * 获取考试界面显示：用户、考试科目，考试时间，题目数量
     * @return
     */
    @Override
    public ExamInfo getExamInfo() {
        ExamInfo examInfo =
                new ExamInfo("JavaSE阶段性考试（一）"
                        ,publicUser,5,questionInfoList.size());

        return examInfo;
    }

    @Override
    public void saveUserAnswer(int index, List<Integer> userAnswers) {
        QuestionInfo questionInfo = questionInfoList.get(index);
        questionInfo.setUserAnswers(userAnswers);
    }

    /**
     * 获取装满用户信息的集合
     *
     * @return
     * @throws IOException
     */
    private ArrayList<User> getArraysList() {
        ArrayList<User> userArrayList = new ArrayList<>();
        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader("user.txt"));
            String line;
            while ((line = br.readLine()) != null) {
                if (!line.startsWith("#")) {
                    String[] split = line.split(":");
                    User user = new User(Integer.parseInt(split[0]), split[1], split[2], split[3], split[4]);
                    userArrayList.add(user);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return userArrayList;
    }


}